﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Super.Common;
using Super.DomainService;
using Super.Entities;
using Super.Infrastructure;
using Super.Mvc;

namespace Super.Web.Areas.Admin.Controllers
{
    public class DiyController : BaseController
    {
        //
        // GET: /Admin/Diy/

        public ActionResult Index()
        {
            var page = Query.Params("pageNum");
            if (string.IsNullOrEmpty(page))
            {
                page = "1";
            }
            var keyword = Query.Post("keyword");
            ViewBag.keyword = keyword;

            var adp = new DbContextAdapter();
            var diyorderService = new DiyOrderService(adp);
            var where = PredicateBuilder.True<DiyOrder>();
            where.And(a => a.IsDel == false);
            if (!string.IsNullOrEmpty(keyword))
            {
                where =
                    where.And(
                        a =>
                        a.OrderNo.Contains(keyword) ||
                        a.User.Name.Contains(keyword) ||
                        a.User.Telephone.Contains(keyword));

            }
            var diyorders = diyorderService.Repository.Find(where).OrderByDescending(a => a.ID).Page(page.ToInt(), PageSize);
            BindPage(diyorders.ItemCount, page.ToInt(), PageSize);
            ViewBag.Records = diyorders.ItemCount;
            return View(diyorders.ItemCollection.ToList());
        }


        public ActionResult Edit()
        {
            var id = Query.Get("id").ToInt(0);
            var adp = new DbContextAdapter();
            var diyorderService = new DiyOrderService(adp);
            var diyComponentsService = new BaseService<DiyComponentsList>(adp);
            var diyorderModel = diyorderService.Repository.Find(a => a.ID == id).FirstOrDefault();
            if (diyorderModel == null)
            {
                return ErrorPage(errorDescription: "未找到此订单！");
            }

            var diycomponentList = diyComponentsService.Repository.Find(a => a.DiyOrder_ID == diyorderModel.ID).ToList();

            ViewBag.DiyComp = diycomponentList;

            var orderTypelist = typeof(DiyOrderTypeEnum).GetItems(diyorderModel.Type);
            ViewBag.DiyOrderType = orderTypelist;

            return View(diyorderModel);
        }

        [HttpPost]
        public JsonResult Edit(DiyOrder model)
        {
            var adp = new DbContextAdapter();
            var diyComponentsService = new BaseService<DiyComponentsList>(adp);
            var diycoms = diyComponentsService.Repository.Find(a => a.DiyOrder_ID == model.ID).ToList();
            foreach (var item in diycoms)
            {
                var w = Query.Post("bx" + item.ID).ToInt(0);
                item.Warrant = w;
                diyComponentsService.Repository.InsertOrUpdate(item);
            }
            adp.SaveChanges();
            return JsonBack.Tip(adp.ErrorMessage);
        }

        #region 模拟装机

        /// <summary>
        /// 模拟装机
        /// </summary>
        /// <returns></returns>
        public ActionResult MoNi()
        {
            var category = new List<string>{
                                 "CPU",
                                 "主板",
                                 "内存",
                                 "硬盘",
                                 "固态硬盘",
                                 "显卡",
                                 "机箱",
                                 "电源",
                                 "散热器",
                                 "显示器",
                                 "鼠标",
                                 "键盘",
                                 "键鼠装",
                                 "音箱",
                                 "光驱",
                                 "声卡",
                                 "网卡"
                             };
            var Multi = new List<string> { "内存", "硬盘", "显卡" };

            var adp = new DbContextAdapter();
            var productCategoryService = new ProductCategoryService(adp);
            var productService = new ProductService(adp);
            var stockService = new StockService(adp);

            //参数接收
            int categoryId = Query.Post("categoryId").ToInt(0);
            var selIds = Query.Get("sel");
            var removeId = Query.Get("remove").ToInt(0);
            var InterfaceTypeId = Query.Post("InterfaceType").ToInt(0);
            var keyword = Query.Post("keyword");
            var priceId = Query.Post("priceId").ToInt(0);

            var categoryList = CacheService.GetDiyCategoryCache();
            if (categoryList == null)
            {
                categoryList = productCategoryService.Repository.Find(a => category.Contains(a.Name)).ToList();
                CacheService.SetDiyCategoryCache(categoryList);
            }
            ViewBag.categoryList = categoryList;
            var temp = categoryList.FirstOrDefault(a => a.ID == categoryId);
            if (temp != null)
                ViewBag.curCagetoryName = temp.Name;
            var muitiIds = categoryList.Where(a => Multi.Contains(a.Name)).Select(j => j.ID);//可以多选的组件

            var where = PredicateBuilder.True<Stock>();
            where = where.And(a => a.IsDel == false);
            where = where.And(a => a.Product.Category_ID == categoryId);
            if (InterfaceTypeId > 0)
            {
                where = where.And(a => a.Product.ProductInterfaceType.Any(i => i.InterfaceType_ID == InterfaceTypeId));
            }
            if (!string.IsNullOrEmpty(keyword))
            {
                where = where.And(a => a.Product.Title.Contains(keyword));
                ViewBag.keyword = keyword;
            }
            if (priceId > 0)
            {
                if (priceId >= 900)
                {
                    where = where.And(a => a.LSPrice > priceId);
                }
                else
                {
                    where = where.And(a => a.LSPrice > priceId && a.LSPrice < priceId + 100);
                }
                ViewBag.priceId = priceId;

            }

            //获取diy列表
            var DiyItemList = CacheService.GetDiyItemList(UserID.ToString());

            //删除已选Diy项目
            if (removeId > 0)
            {
                var removeItem = DiyItemList.Where(a => a.CategoryId == removeId).ToList();
                foreach (var item in removeItem)
                {
                    DiyItemList.Remove(item);
                }

            }

            //设置当前分类
            if (categoryId == 0)
            {
                var j = CacheService.GetOneCache("curCategoryId");
                if (j != null)
                {
                    categoryId = j;
                }
            }
            CacheService.SetOneCache("curCategoryId", categoryId);
            ViewBag.curCategoryId = categoryId;

            //处理选择Diy项
            if (!string.IsNullOrEmpty(selIds))
            {
                var j = selIds.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                var item = new DiyItem
                               {
                                   ProductId = j[0].ToInt(0),
                                   Price = j[1].ToDecimal(0),
                                   ProductName = j[2],
                                   CategoryId = j[3].ToInt(0),
                                   Warrant = j[4].ToInt(0)
                               };
                if (!muitiIds.Any(a => a == item.CategoryId))
                {
                    var removeItem = DiyItemList.FirstOrDefault(a => a.CategoryId == item.CategoryId);
                    DiyItemList.Remove(removeItem);
                }
                DiyItemList.Add(item);
            }

            CacheService.SetDiyItemList(UserID.ToString(), DiyItemList);
            ViewBag.totalPrice = DiyItemList.Sum(item => item.Price);
            ViewBag.DiyItems = DiyItemList;
            // var productList = productService.Repository.Find(a => a.Category_ID == categoryId).ToList();
            var stockList = stockService.Repository.Find(where).ToList();
            GetInterFaceType(InterfaceTypeId);
            var orderTypelist = typeof(DiyOrderTypeEnum).GetItems();
            ViewBag.DiyOrderType = orderTypelist;
            return View(stockList);
        }

        [HttpPost]
        public JsonResult SaveDiyOrder()
        {

            //获取diy列表
            var DiyItemList = CacheService.GetDiyItemList(UserID.ToString());
            if (DiyItemList == null)
            {
                return JsonBack.Tip("请选择配件！");
            }

            var diyorderType = Query.Post("DiyOrderType").ToInt(0);
            var userId = Query.Post("userId");
            var remark = Query.Post("remark");
            var totalPrice = Query.Post("totalPrice").ToDecimal(0);

            var adp = new DbContextAdapter();
            var diyorderService = new DiyOrderService(adp);
            var diycomponentService = new BaseService<DiyComponentsList>(adp);
            var categoryService = new ProductCategoryService(adp);
            var cpuCagetory = categoryService.Repository.Find(a => a.Name.Contains("CPU")).FirstOrDefault();
            if (cpuCagetory == null)
            {
                return JsonBack.Tip("不存在CPU分类！");
            }


            var cpuId = cpuCagetory.ID;
            var cpu = DiyItemList.FirstOrDefault(a => a.CategoryId == cpuId);
            if (cpu == null)
            {
                return JsonBack.Tip("没有选择CPU！");
            }

            var diyOrderModel = new DiyOrder();
            diyOrderModel.CreateTime = DateTime.Now;
            diyOrderModel.Type = diyorderType;
            diyOrderModel.OrderNo = Number.GetSerialNumber().ToString();
            diyOrderModel.Price = totalPrice;
            diyOrderModel.LetMoney = 0;
            diyOrderModel.Remark = remark;
            diyOrderModel.Name = cpu.ProductName + "||" +
                                 DateTime.Now.ToShortDateString();

            if (string.IsNullOrEmpty(userId))
            {
                var userService = new UserService(adp);
                var userModel = userService.Repository.Find(a => a.UID == userId).FirstOrDefault();
                if (userModel != null)
                {
                    diyOrderModel.User_ID = userModel.ID;
                }
            }

            diyorderService.Repository.InsertOrUpdate(diyOrderModel);

            foreach (var item in DiyItemList)
            {
                var model = new DiyComponentsList();
                model.DiyOrder_ID = diyOrderModel.ID;
                model.Product_ID = item.ProductId;
                model.Warrant = item.Warrant;
                diycomponentService.Repository.InsertOrUpdate(model);
            }


            adp.SaveChanges();
            if (adp.ErrorMessage == null)
            {
                CacheService.DiyItemsCache.Remove(UserID.ToString());//清楚这次装机缓存
            }
            return JsonBack.Tip(adp.ErrorMessage);

        }


        #endregion

        #region 购买
        /// <summary>
        /// 购买此订单
        /// </summary>
        /// <returns></returns>
        public ActionResult Buy()
        {
            var id = Query.Get("id").ToInt();
            var adp = new DbContextAdapter();
            var diyorderService = new DiyOrderService(adp);
            var diyComponentsService = new BaseService<DiyComponentsList>(adp);

            var diyorderModel = diyorderService.Repository.Find(a => a.ID == id).FirstOrDefault();
            if(diyorderModel==null)
            {
                return ErrorPage(errorDescription: "Wa Kao!没找到这个订单");
            }
            if (diyorderModel.User != null)
            {
                return ErrorPage(errorDescription: "这个订单已经有主了！");
            }
            var diycomponentList = diyComponentsService.Repository.Find(a => a.DiyOrder_ID == diyorderModel.ID).ToList();

            ViewBag.DiyComp = diycomponentList;

            var orderTypelist = typeof(DiyOrderTypeEnum).GetItems(diyorderModel.Type);
            ViewBag.DiyOrderType = orderTypelist;

            return View(diyorderModel);
        }

        [HttpPost]
        public JsonResult Buy(DiyOrder model)
        {
            var userId = Query.Post("user.ID").ToInt(0);
            var name = Query.Post("Name");
            var payMoney = Query.Post("PayMoney").ToDecimal(0);
            if (userId == 0)
            {
                return JsonBack.Tip("请选择用户！");
            }
            if (payMoney == 0)
            {
                return JsonBack.Tip("请输入支付金额！");
            }
            var adp = new DbContextAdapter();
            var diyorderService = new DiyOrderService(adp);
            var diyComponentService = new BaseService<DiyComponentsList>(adp);
            var stockService = new StockService(adp);
            var payService = new PayService(adp);
            var moneyChangeService = new MoneyChangeTypeService(adp);

            var moneyChange = moneyChangeService.GetStockChangeModel("装机",MoneyChangeTypeEnum.In);

            var diyorderModel = diyorderService.Repository.Find(a => a.ID == model.ID).FirstOrDefault();
            if (diyorderModel == null)
            {
                return JsonBack.Tip("没有找到词装机单！");
            }
            diyorderModel.LetMoney = diyorderModel.Price - payMoney;
            diyorderModel.PayMoney = payMoney;
            diyorderModel.User_ID = userId;
            diyorderModel.PayTime = DateTime.Now;
            diyorderService.Repository.InsertOrUpdate(diyorderModel);

            var diycomponents = diyComponentService.Repository.Find(a => a.DiyOrder_ID == diyorderModel.ID).ToList();
            var diycomIds = diycomponents.Select(a => a.ID).ToList();
            var stocks = stockService.Repository.Find(a => diycomIds.Contains(a.Product_ID)).ToList();
           
            //跟新产品库存
            foreach (var stock in stocks)
            {
                if(stock.Count>0)
                {
                    stock.Count -= 1;
                    stockService.Repository.InsertOrUpdate(stock);
                }
            }

            //更新产品的有效期
            foreach (var item in diycomponents)
            {
                var w = Query.Post("bx" + item.ID).ToInt(0);
                item.Warrant = w;
                diyComponentService.Repository.InsertOrUpdate(item);
            }

            //添加支付记录
            var payModel = new PayRecord();
            payModel.OrderNo = diyorderModel.OrderNo;//?todo://斟酌
            payModel.TradeNo = Number.GetSerialNumber().ToString();
            payModel.Subject = "DIY装机";
            payModel.Money = diyorderModel.PayMoney > 0 ? diyorderModel.PayMoney.Value : 0;
            payModel.MoneyChangeType_ID = moneyChange.ID;
            payModel.CreateTime = DateTime.Now;
            payService.Repository.InsertOrUpdate(payModel);

            adp.SaveChanges();
            return JsonBack.Tip(adp.ErrorMessage, "diyIndex");
        }

        #endregion
    }
}
